package org.example.esdemo.service;

import org.example.esdemo.entity.Product;
import org.example.esdemo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    // 保存产品
    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    // 批量保存产品
    public Iterable<Product> saveAllProducts(Iterable<Product> products) {
        return productRepository.saveAll(products);
    }

    // 根据ID查询产品
    public Optional<Product> getProductById(String id) {
        return productRepository.findById(id);
    }

    // 查询所有产品
    public Iterable<Product> getAllProducts() {
        return productRepository.findAll();
    }

    // 根据名称查询
    public List<Product> getProductsByName(String name) {
        return productRepository.findByName(name);
    }

    // 根据分类查询
    public List<Product> getProductsByCategory(String category) {
        return productRepository.findByCategory(category);
    }

    // 多条件查询
    public List<Product> getProductsByNameAndCategory(String name, String category) {
        return productRepository.findByNameAndCategory(name, category);
    }

    // 价格区间查询(分页)
    public Page<Product> getProductsByPriceBetween(BigDecimal minPrice, BigDecimal maxPrice, Pageable pageable) {
        return productRepository.findByPriceBetween(minPrice, maxPrice, pageable);
    }

    // 删除产品
    public void deleteProduct(String id) {
        productRepository.deleteById(id);
    }
}
